﻿using Lg.Core.Extensions;
using Lg.Core.Form;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using NPOI.XSSF.Streaming.Values;
using Org.BouncyCastle.Asn1.Ocsp;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lg.Core
{
    public class Data
    {
        #region [从请求的request中获取post参数和值]
        /// <summary>
        /// 从请求的request中获取post参数和值(支付宝回调验签需要该字典格式)
        /// </summary>
        /// <returns>Dictionary</returns>
        public static Dictionary<string, string> GetRequest(HttpRequest request)
        {
            if (request.ContentType == "application/json")
            {
                throw new Exception("无法解析\"ContentType\"为\"application/json\"的参数！");
            }
            string method = request.Method.ToUpper();
            Dictionary<string, string> sArray = new Dictionary<string, string>();
            switch (method)
            {
                case "GET":
                    IQueryCollection queryCollection = request.Query;
                    foreach (var item in queryCollection)
                    {
                        sArray.Add(item.Key, item.Value);
                    }
                    break;
                case "POST":
                    IFormCollection formCollection = request.Form;
                    foreach (var item in formCollection)
                    {
                        sArray.Add(item.Key, item.Value);
                    }
                    break;

            }
            return sArray;
        }
        #endregion

        #region [从请求的request中获取指定实体中包含的属性名称集合]
        /// <summary>
        /// 从请求的request中获取指定实体中包含的属性名称集合
        /// </summary>
        /// <returns>string[]</returns>
        public static string[] GetPostParamInModel<T>(HttpRequest request)
        {
            Type type = typeof(T);
            var properties = type.GetProperties();
            IFormCollection coll = request.Form;
            return coll.Keys.Where(p => properties.AsParallel().Where(r => r.Name.ToLower() == p.ToLower()).Any()).ToArray();
        }
        #endregion

        public static T GetModelFormRequest<T>(HttpRequest request) where T : new()
        {
            var t = new T();
            IFormCollection coll = request.Form;
            var properties = t.GetType().GetProperties();
            foreach (var kv in coll)
            {
                var pi = properties.FirstOrDefault(p => p.Name == kv.Key);
                if (pi != null)
                {
                    if (pi.PropertyType.IsGenericType)
                    {
                        var piType = pi.PropertyType.GetGenericArguments()[0];
                        if (!string.IsNullOrEmpty(kv.Value))
                        {
                            var value = Convert.ChangeType(Convert.ToString(kv.Value), piType);
                            pi.SetValue(t, value);
                        }
                        else
                        {
                            pi.SetValue(t, null);
                        }
                    }
                    else
                    {
                        var value = Convert.ChangeType(Convert.ToString(kv.Value), pi.PropertyType);
                        pi.SetValue(t, value);
                    }
                }
            }
            return t;
        }

        /// <summary>
        /// 获取包含自定义表单的分页查询条件
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static Dictionary<string, object> GetDiyFormQueryParams(HttpRequest request)
        {
            //初始化默认参数
            var initDict = new Dictionary<string, object>();
            initDict.Add("IsDelete", 0);
            initDict.Add("Page", 1);
            initDict.Add("Limit", 10);
            //将要返回出去的数据容易
            Dictionary<string, object> result = new Dictionary<string, object>();
            foreach (var item in request.Query)
            {
                if (!string.IsNullOrEmpty(item.Value))
                {
                    result.Add(item.Key, item.Value);
                }
            }
            //遍历传入的参数是否包含默认参数,如果不包含,就添加进去
            foreach (var item in initDict)
            {
                var exist = result.Keys.Any(k => k == item.Key);
                if (!exist)
                {
                    result.Add(item.Key, item.Value);
                }
            }
            return result;
        }

        /// <summary>
        /// 从请求中获取自定义表单的分页查询条件
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static List<SearchParam> GetSearchParamsByRequest(HttpRequest request)
        {
            //初始化默认参数
            var initList = new List<SearchParam>();
            initList.Add(new SearchParam() { Name="IsDelete",Value="0"});
            //将要返回出去的数据容易
            var list = new List<SearchParam>();
            foreach (var item in request.Query)
            {
                if (!string.IsNullOrEmpty(item.Value))
                {
                    list.Add(new SearchParam { Name=item.Key,Value=item.Value});
                }
            }
            //遍历传入的参数是否包含默认参数,如果不包含,就添加进去
            foreach (var initItem in initList)
            {
                var exist = list.Any(l=>l.Name== initItem.Name);
                if (!exist)
                {
                    list.Add(initItem);
                }
            }
            return list;
        }

        /// <summary>
        /// 在datatable里进行分页.返回分页需要的数据
        /// </summary>
        /// <param name="table"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public static DataTable? TablePager(DataTable table,int page,int limit)
        {
            var rows = new List<DataRow>();
            int min = (page - 1) * limit;
            int max = page * limit-1;
            for (int i = min; i <= max; i++)
            {
                if (i<table.Rows.Count)
                {
                    rows.Add(table.Rows[i]);
                }
                else
                {
                    break;
                }
            }
            if (rows.Any())
            {
                return rows.CopyToDataTable();
            }
            else
            {
                return null;
            }
        }


    }
}
